import torch
import torch.nn as nn
import torch.nn.functional as F
import pywt


class ChannelWiseCNN(nn.Module):
    def __init__(self, input_dim, hidden_dim, latent_dim, num_layers):
        super(ChannelWiseCNN, self).__init__()

        self.conv_layers = nn.Sequential(
            nn.Conv1d(1, 4, kernel_size=16, stride=1),  # 17,18
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=7, stride=7),  # 7,7 8,7

            nn.Conv1d(4, 8, kernel_size=13, stride=1),  # kernel=9,11,13,channel=8,16
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=7, stride=7),

            nn.Conv1d(8, 16, kernel_size=7, stride=1),  # kernel=9,11
            nn.ReLU(),
            nn.MaxPool1d(kernel_size=6, stride=6)
        )

        # 计算全连接层的输入尺寸
        sample_input = torch.zeros(1, 1, 2560)
        sample_output = self.conv_layers(sample_input)
        flattened_size = sample_output.view(1, -1).size(1)

        # 定义全连接层
        self.fc1 = nn.Linear(flattened_size, 128)
        #dropout
        self.dropout = nn.Dropout(0)#0.1,0.2
        self.fc2 = nn.Linear(128, 1)

    def forward(self, x):
        # x形状：[batch_size, 1, 2560]
        x = self.conv_layers(x)
        x = x.view(x.size(0), -1)
        x = torch.relu(self.fc1(x))
        x = self.dropout(x)
        x = self.fc2(x)
        return x



# VGG 块的构建函数
def vgg_block1d(num_convs, in_channels, out_channels):
    layers = []
    for _ in range(num_convs):
        layers.append(nn.Conv1d(in_channels, out_channels, kernel_size=3, padding=1))
        layers.append(nn.ReLU())
        layers.append(nn.BatchNorm1d(out_channels))  # 批归一化
        in_channels = out_channels
    layers.append(nn.MaxPool1d(kernel_size=2, stride=2))  # 最大池化
    return nn.Sequential(*layers)

# 通用 VGG 模型构建函数
def vgg1d(conv_arch, fc_features, fc_hidden_units, num_classes=7):
    conv_blks = []
    in_channels = 1  # 假设输入为单通道信号
    
    for (num_convs, out_channels) in conv_arch:
        conv_blks.append(vgg_block1d(num_convs, in_channels, out_channels))
        in_channels = out_channels
    
    return nn.Sequential(
        *conv_blks,
        nn.Flatten(),
        nn.Linear(fc_features, fc_hidden_units),
        nn.ReLU(),
        nn.Dropout(0.5),
        nn.Linear(fc_hidden_units, fc_hidden_units),
        nn.ReLU(),
        nn.Dropout(0.5),
        nn.Linear(fc_hidden_units, num_classes)
    )

# 定义特定的 VGG 模型类
class VGG13_1D(nn.Module):
    def __init__(self, num_classes=1):
        super(VGG13_1D, self).__init__()
        conv_arch = ((2, 64), (2, 128), (2, 256), (2, 512))
        fc_features = 512 * (2560 // (2**4))  # 根据池化次数调整
        fc_hidden_units = 1024
        self.model = vgg1d(conv_arch, fc_features, fc_hidden_units, num_classes)

    def forward(self, x):
        return self.model(x)

# 可以根据需要定义更多 VGG 模型，例如 VGG16_1D, VGG19_1D 等
class VGG16_1D(nn.Module):
    def __init__(self, num_classes=1):
        super(VGG16_1D, self).__init__()
        conv_arch = ((2, 64), (2, 128), (3, 256), (3, 512))
        fc_features = 512 * (2560 // (2**4))
        fc_hidden_units = 1024
        self.model = vgg1d(conv_arch, fc_features, fc_hidden_units, num_classes)

    def forward(self, x):
        return self.model(x)

class VGG19_1D(nn.Module):
    def __init__(self, num_classes=1):
        super(VGG19_1D, self).__init__()
        conv_arch = ((2, 64), (2, 128), (4, 256), (4, 512))
        fc_features = 512 * (2560 // (2**4))
        fc_hidden_units = 1024
        self.model = vgg1d(conv_arch, fc_features, fc_hidden_units, num_classes)

    def forward(self, x):
        return self.model(x)
    

#定义 BasicBlock1D 和 ResNet1D，接受单通道输入
class BasicBlock1D(nn.Module):
    def __init__(self, in_channels, out_channels, stride=1):
        super(BasicBlock1D, self).__init__()
        self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm1d(out_channels)
        self.relu = nn.ReLU(inplace=True)
        
        self.conv2 = nn.Conv1d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn2 = nn.BatchNorm1d(out_channels)
        
        self.downsample = None
        if stride != 1 or in_channels != out_channels:
            self.downsample = nn.Sequential(
                nn.Conv1d(in_channels, out_channels, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm1d(out_channels)
            )
        
    def forward(self, x):
        identity = x
        
        out = self.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        
        if self.downsample is not None:
            identity = self.downsample(x)
        
        out += identity
        out = self.relu(out)
        
        return out

class ResNet1D(nn.Module):
    def __init__(self, block, layers, num_classes=1):
        super(ResNet1D, self).__init__()
        self.in_channels = 64
        self.conv1 = nn.Conv1d(1, 64, kernel_size=5, stride=2, padding=2, bias=False)
        self.bn1 = nn.BatchNorm1d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool1d(kernel_size=7, stride=2, padding=3)
        
        self.layer1 = self._make_layer(block, 64,  layers[0], stride=1)
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
        
        self.global_avg_pool = nn.AdaptiveAvgPool1d(1)
        self.fc = nn.Linear(512, num_classes)
    
    def _make_layer(self, block, out_channels, blocks, stride):
        layers = []
        layers.append(block(self.in_channels, out_channels, stride))
        self.in_channels = out_channels
        for _ in range(1, blocks):
            layers.append(block(out_channels, out_channels))
        return nn.Sequential(*layers)
    
    def forward(self, x):
        # x 形状: [batch_size, 1, 2560]
        x = self.relu(self.bn1(self.conv1(x)))   # [batch_size, 64, 1280]
        x = self.maxpool(x)                      # [batch_size, 64, 640]
        
        x = self.layer1(x)  # [batch_size, 64, 640]
        x = self.layer2(x)  # [batch_size, 128, 320]
        x = self.layer3(x)  # [batch_size, 256, 160]
        x = self.layer4(x)  # [batch_size, 512, 80]
        
        x = self.global_avg_pool(x)  # [batch_size, 512, 1]
        x = x.view(x.size(0), -1)    # [batch_size, 512]
        x = self.fc(x)               # [batch_size, num_classes]
        return x

# 定义不同深度的 ResNet1D 模型
class ResNet18_1D(ResNet1D):
    def __init__(self, num_classes=1):
        super(ResNet18_1D, self).__init__(BasicBlock1D, [2, 2, 2, 2], num_classes)

class ResNet34_1D(ResNet1D):
    def __init__(self, num_classes=1):
        super(ResNet34_1D, self).__init__(BasicBlock1D, [3, 4, 6, 3], num_classes)